#include "Poco/Net/Socket.h"
#include "Poco/Net/IPAddress.h"
#include "Poco/Net/SocketAddress.h"
#include "Poco/Format.h"
#include "Poco/Timespan.h"
#include "Poco/Net/NetException.h"
#include <iostream>
#include <vector>
#include <string>
#include <stdlib.h>
using namespace std;
using Poco::Net::IPAddress;
using Poco::Net::SocketAddress;
using Poco::Net::Socket;
using Poco::Timespan;

int main(int argc, char** argv)
{
	if (argc < 2)
	{
		cout<<"usage:./client connect_count"<<endl;
		return 0;
	}
	// set-up a server socket
	IPAddress	ip("127.0.0.1");
	Poco::UInt16 port = 7000;
	SocketAddress addr(ip,port);
	vector<Socket*> sockets;
	int conn_count = atoi(argv[1]);
	
	//Timespan	recvTimeout(1,0);
	for(int i = 0; i < conn_count; i++)
	{
		try{
			Socket* pSocket = new Socket();
			if (pSocket->connect(addr) != 0 || pSocket->sockfd() < 0)
				cout<<"connect failed,i="<<i<<endl;
			else
			{
				sockets.push_back(pSocket);
				//pSocket->setRecvTimeout(recvTimeout);
			}
		}
		catch(...)
		{
			break;
		}
	}
	cout<<"conn_count:"<<conn_count<<endl;
	sleep(2);
	for(int i = 0; i < conn_count;i++)
	{
		cout<<"sockfd="<<sockets[i]->sockfd()<<endl;
		
		string text = Poco::format("hello from %d",sockets[i]->sockfd());
		int sendbyte = sockets[i]->sendBytes(text.c_str(),text.size());
		if (sendbyte < 0)
		{
			cout<<"send error"<<endl;
			continue;
		}
		//cout<<"sendbyte:"<<sendbyte<<endl;
		char buf[64] = {0};
		int len = 0;
		try{
			while(	sockets[i] != NULL && ( len = sockets[i]->recvBytes(buf,63)) > 0)
			{
				if (len == 63)
				{
					cout<<buf<<endl;
					continue;
				}
				else
				{
					cout<<buf<<endl;
				}
				break;
			}
		}
		catch(Poco::TimeoutException& e)
		{
			cout<<"TimeoutException close fd:"<<sockets[i]->sockfd()<<endl;
			sockets[i]->close();
		}
		catch (Poco::Net::InvalidSocketException& e)
		{
			cout<<"invalid socket"<<endl;
		}
		catch(...)
		{
			cout<<"close fd"<<sockets[i]->sockfd()<<endl;
			sockets[i]->close();
		}
		// 第二次发送
		sendbyte = sockets[i]->sendBytes(text.c_str(),text.size());
		if (sendbyte < 0)
		{
			cout<<"send error"<<endl;
			continue;
		}
		//cout<<"sendbyte:"<<sendbyte<<endl;
		memset(buf,sizeof(buf),0);
		len = 0;
		try{
			while(	sockets[i] != NULL && ( len = sockets[i]->recvBytes(buf,63)) > 0)
			{
				if (len == 63)
				{
					cout<<buf<<endl;
					continue;
				}
				else
				{
					cout<<buf<<endl;
				}
				break;
			}
		}
		catch(Poco::TimeoutException& e)
		{
			cout<<"TimeoutException close fd:"<<sockets[i]->sockfd()<<endl;
			sockets[i]->close();
		}
		catch (Poco::Net::InvalidSocketException& e)
		{
			cout<<"invalid socket"<<endl;
		}
		catch(...)
		{
			cout<<"close fd"<<sockets[i]->sockfd()<<endl;
			sockets[i]->close();
		}
	}
	cout<<"close sockets"<<endl;
	for (int i = 0 ; i < conn_count;i++)
	{
		if (sockets[i]->sockfd() != -1)
			sockets[i]->close();
	}
	
	return 0;
}
	


	
	
	
	
	
	
	
	
	
	
	
	
